package com.boot.controller;

import com.boot.entity.*;
import com.boot.repository.MajorRepository;
import com.boot.repository.SchoolRepository;
import com.boot.repository.TeaInfoRepository;
import com.boot.util.CSVUtils;
import com.boot.util.Constants;
import com.boot.util.StringUtil;
import com.boot.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.transaction.Transactional;
import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@RestController
@CrossOrigin(origins = "*")

@RequestMapping("/tea")
public class TeaInfoController {

    String namerex = "^[A-z\\u4e00-\\u9fa5]*$";
    Pattern regexName = Pattern.compile(namerex);

    public static final String REGEX_PASSWORD = "^(?![\\d]+$)(?![a-zA-Z]+$)(?![-_]+$)[\\da-zA-Z-_]{6,32}$";
    Pattern regPassword = Pattern.compile(REGEX_PASSWORD);

    String emailXX = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
    Pattern regexemail = Pattern.compile(emailXX);

    public static final String REGEX_MOBILE = "^((17[0-9])|(14[0-9])|(13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$";
    Pattern regexphone = Pattern.compile(REGEX_MOBILE);

    public static final String REGEX_ID_CARD = "(^\\d{18}$)|(^\\d{15}$)";
    Pattern regexCard = Pattern.compile(REGEX_ID_CARD);

    @Autowired
    private TeaInfoRepository teaInfoRepository;

    @Autowired
    private SchoolRepository schoolRepository;

    @Autowired
    private MajorRepository majorRepository;


    @RequestMapping("/teaInfo")
    public BaseMessage<?> teaInfo(String name) {
        List<TeaInfo> all;
        List<TeaInfoVO> allTeaVO=new ArrayList<>();
        if (StringUtils.isEmpty(name)) {
            all = teaInfoRepository.findAll();
        } else {
            all = teaInfoRepository.findAllByWorkNumber(name);
        }
        for(TeaInfo teaInfo:all)
            allTeaVO.add(teaInfoToTeaInfoVO(teaInfo));
        return MessageHandler.createSuccessVo(allTeaVO, "success");
    }

    @RequestMapping("/getByName")
    public BaseMessage<?> getByName(String name) {
        return MessageHandler.createSuccessVo(teaInfoRepository.findByWorkNumber(name), "success");
    }

    /**
     * 导入csv 批量添加数据
     *
     * @return
     */
    @PostMapping(value = "/importCsv")
    public BaseMessage<?> upload(@RequestParam("file") MultipartFile file) {
        try {
            //上传内容不能为空
            if (file.isEmpty()) {
                return MessageHandler.createFailedVo("文件内无数据！");
            }
            File newFile = CSVUtils.uploadFile(file);
            List<List<String>> userRoleLists = CSVUtils.readCSV(newFile.getPath(), 5);

            ArrayList<String> names = new ArrayList<>();

            userRoleLists.forEach(e -> {
                TeaInfo teaInfo = new TeaInfo();
                teaInfo.setName(e.get(0));
                teaInfo.setWorkNumber(e.get(1));
                if (StringUtils.isNoneEmpty(e.get(2))) {
                    teaInfo.setPhoneNumber(e.get(2));
                }
                if (StringUtils.isNoneEmpty(e.get(3))) {
                    teaInfo.setEmail(e.get(3));
                }
                if (StringUtils.isNoneEmpty(e.get(4))) {
                    teaInfo.setIdCard(e.get(4));
                }
                if (StringUtils.isNoneEmpty(e.get(5))) {
                    teaInfo.setIdCard(e.get(5));
                }
                if (StringUtils.isNoneEmpty(e.get(6))) {
                    teaInfo.setIdCard(e.get(6));
                }
                teaInfo.setPassword(Constants.DEFAULT_PASSWORD);
                teaInfo.setType(Constants.TEA_ROLE);
                String check = check(teaInfo);
                if (check.equals("0")) {
                    teaInfoRepository.save(teaInfo);
                } else {
                    names.add(teaInfo.getName());
                }

            });
            newFile.delete();
            return MessageHandler.createSuccessVo("操作成功"+( names.size() > 0 ?"沒有添加成功的教師姓名有："+ names.stream().collect(Collectors.joining(",")) : ""));
        } catch (Exception e) {
            e.printStackTrace();
            return MessageHandler.createFailedVo(e.getMessage());
        }

    }

    @RequestMapping("/saveTea")
    public BaseMessage<?> saveTea(@RequestBody TeaInfo teaInfo) {
        return insertTea(teaInfo);
    }

    private BaseMessage<String> insertTea(TeaInfo teaInfo) {
        String check = check(teaInfo);
        if (check.startsWith("1")) {
            return MessageHandler.createFailedVo(check.substring(1));
        }
        //设置默认密码、状态、身份
        if (StringUtils.isBlank(teaInfo.getPassword())) {
            teaInfo.setPassword(Constants.DEFAULT_PASSWORD);
        }
        teaInfo.setStatus(true);
        teaInfo.setType(Constants.TEA_ROLE);
        teaInfoRepository.save(teaInfo);

        Major major = majorRepository.getById(teaInfo.getMajorId());
        if (major != null) {
            major.setStuNum(major.getStuNum() + 1);
            majorRepository.save(major);
        }
        return MessageHandler.createSuccessVo("操作成功,您的初始密码为:" + Constants.DEFAULT_PASSWORD);
    }

    private String check(TeaInfo teaInfo) {
        if (StringUtil.isBlank(teaInfo.getName())) {
            return "1" + "姓名填写不正确";
        }
        if (StringUtil.isNotBlank(teaInfo.getName()) && !regexName.matcher(teaInfo.getName()).matches()) {
            return "1" + "姓名只能包含中英文";
        }
        if (StringUtil.isBlank(teaInfo.getWorkNumber())) {
            return "1" + "工号填写不正确";
        }

        if (StringUtil.isNotBlank(teaInfo.getPassword()) && !regPassword.matcher(teaInfo.getPassword()).matches()) {
            return "1" + "密码长度为6-32个字符；\n" +
                    "字母，数字或者特殊字符（-_）至少包含两种";
        }
        if (StringUtil.isBlank(teaInfo.getIdCard())) {
            return "1" + "身份证不能为空";
        }
        if (StringUtil.isNotBlank(teaInfo.getEmail()) && !regexemail.matcher(teaInfo.getEmail()).matches()) {
            return "1" + "邮箱不正确";
        }
        if (StringUtil.isNotBlank(teaInfo.getPhoneNumber()) && !regexphone.matcher(teaInfo.getPhoneNumber()).matches()) {
            return "1" + "手机号码格式不正确";
        }
        if (StringUtil.isNotBlank(teaInfo.getIdCard()) && !regexCard.matcher(teaInfo.getIdCard()).matches()) {
            return "1" + "身份证号格式不正确";
        }
        Calendar cal = Calendar.getInstance();
        int year = (cal.get(Calendar.YEAR)) % 100;  //年份的后两位
        String regYear = teaInfo.getWorkNumber().substring(0, 2);   // 取出前两位为注册年份
        if (StringUtil.isNotBlank((teaInfo.getWorkNumber()))  //学号非空
                && !(regYear.equals(year + "") &&
                (teaInfo.getWorkNumber().length()) == Constants.WORKNUMBER_LENGTH)) {    //前两位为注册年份&&学号长度正确
            return "1" + "工号格式不正确";
        }
        if (teaInfoRepository.existsByWorkNumber(teaInfo.getWorkNumber()) == true) {
            return "1" + "该教师已注册";
        }
        if (null == teaInfo.getSchoolId()) {
            return "1" + "学院id不能为空";
        }
        if (null == teaInfo.getMajorId()) {
            return "1" + "专业id不能为空";
        }
        if(false==schoolRepository.existsBySchoolId(teaInfo.getSchoolId()))
            return "1"+"该学院不存在";
        if(false==majorRepository.existsByMajorId(teaInfo.getMajorId()))
            return "1" + "该专业不存在";
        return "0";
    }

    //教师修改手机email
    @Transactional
    @RequestMapping("/updateTea")
    public BaseMessage<?> updateTea(@RequestBody ResTelAndEmail newInfo) {
        TeaInfo ttt = teaInfoRepository.findByWorkNumber(newInfo.getNumber());
        if (StringUtil.isNotBlank(newInfo.getEmail()) && !regexemail.matcher(newInfo.getEmail()).matches()) {
            return MessageHandler.createFailedVo("邮箱不正确");
        }
        if (StringUtil.isNotBlank(newInfo.getPhone()) && !regexphone.matcher(newInfo.getPhone()).matches()) {
            return MessageHandler.createFailedVo("手机号码格式不正确");
        }
        teaInfoRepository.save(ttt);
        return MessageHandler.createSuccessVo("修改手机/email成功");
    }


    //教室修改密码
    @RequestMapping("" +
            "")
    public BaseMessage<?> changePwdTea(@RequestBody RestPwdVO restPwdVO) {
        if (restPwdVO.getNumber().length() != Constants.WORKNUMBER_LENGTH) {
            return MessageHandler.createFailedVo("工号格式不对");
        }
        if (teaInfoRepository.existsByWorkNumber(restPwdVO.getNumber()) == false) {
            return MessageHandler.createFailedVo("该学生不存在");
        }
        TeaInfo uuu = teaInfoRepository.findByWorkNumber(restPwdVO.getNumber());
        if (StringUtil.isBlank(restPwdVO.getOldPassword())) {
            return MessageHandler.createFailedVo("旧密码不能为空");
        }
        if (StringUtil.isBlank(restPwdVO.getNewPassword())) {
            return MessageHandler.createFailedVo("新密码不能为空");
        }
        if (StringUtil.isNotBlank(restPwdVO.getNewPassword()) && !regPassword.matcher(restPwdVO.getNewPassword()).matches()) {
            return MessageHandler.createFailedVo("密码长度为6-32个字符；\n" +
                    "字母，数字或者特殊字符（-_）至少包含两种");
        }
        if (StringUtil.isBlank(restPwdVO.getConfirmPassword())) {
            return MessageHandler.createFailedVo("确认密码不能为空");
        }
        if (!restPwdVO.getConfirmPassword().equals(restPwdVO.getNewPassword())) {
            return MessageHandler.createFailedVo("确认密码与新密码不一致");
        }
        if (!restPwdVO.getOldPassword().equals(uuu.getPassword())) {
            return MessageHandler.createFailedVo("旧密码错误");
        }
        uuu.setPassword(restPwdVO.getNewPassword());
        teaInfoRepository.save(uuu);
        return MessageHandler.createSuccessVo("密码修改成功");
    }


    /**
     * 删除
     */
    @Transactional
    @DeleteMapping("delTea/{workNum}")
    public BaseMessage delTea(@PathVariable String workNum) {
        TeaInfo teaInfo = teaInfoRepository.findByWorkNumber(workNum);
        School s = schoolRepository.findBySchoolId(teaInfo.getSchoolId());
        int a = s.getTeaNum();
        a--;
        s.setTeaNum(a);
        schoolRepository.save(s);
        Major m = majorRepository.findByMajorId(teaInfo.getMajorId());
        int b = m.getTeaNum();
        b--;
        m.setTeaNum(b);
        majorRepository.save(m);
        teaInfoRepository.delete(teaInfo);
        return MessageHandler.createSuccessVo("操作成功");
    }

    @ResponseBody
    @RequestMapping("/changeTeaStatus")
    public BaseMessage<?> changeTeaStatus(@RequestParam String workNum, Boolean status) {
        if (status == false)   //目前只考虑到在职离职，后续若有第三状态，则将Boolean改成Integer即可
            delTea(workNum);
        return MessageHandler.createSuccessVo("教师离职");
    }

    //管理员修改个人信息
    @ResponseBody
    @RequestMapping("/amdinEdit")
    public BaseMessage<?> adminEdit(@RequestBody TeaInfo teaInfo){
        String check = check(teaInfo);
        if (check.startsWith("1"))
            return MessageHandler.createFailedVo(check.substring(1));
        teaInfoRepository.save(teaInfo);
        return   MessageHandler.createSuccessVo("修改成功" );
    }


    public TeaInfoVO teaInfoToTeaInfoVO(TeaInfo teaInfo){
        Major major=majorRepository.findByMajorId(teaInfo.getMajorId());
        School school=schoolRepository.findBySchoolId(teaInfo.getSchoolId());
        TeaInfoVO vo=new TeaInfoVO();
        vo.setName(teaInfo.getName());                  vo.setWorkNumber(teaInfo.getWorkNumber());
        vo.setPhoneNumber(teaInfo.getPhoneNumber());    vo.setEmail(teaInfo.getEmail());
        vo.setIdCard(teaInfo.getIdCard());              vo.setPassword(teaInfo.getPassword());
        vo.setMajorName(major.getMajorName());          vo.setSchoolName(school.getSchoolName());
        vo.setStatus(teaInfo.getStatus());              vo.setChangePassword(teaInfo.getChangePassword());
        vo.setType(teaInfo.getType());
        return vo;
    }


}
